package lab.domain;

import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;

@XmlAccessorType(XmlAccessType.FIELD)
public abstract class Record<T extends Record> implements Serializable {
    @XmlAttribute
    protected int id;
    
    private transient ChangeListener listener;

    public Record() {
    }

    public Record(T record) {
        copy(record);
    }

    public int getId() {
        return id;
    }
    
    public void setId(int id) {
        this.id = id;
        notifyChanged();
    }

    public ChangeListener getListener() {
        return listener;
    }

    public void setListener(ChangeListener listener) {
        this.listener = listener;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj != null && getClass().equals(obj.getClass())) {
            return id == ((Record)obj).getId();
        }
        return false;
    }

    @Override
    public int hashCode() {
        return id;
    }
    
    @Override
    public Record clone() {
        Record record = null;
        try {
             record = this.getClass().newInstance();
             record.id = id;
        } catch (Exception ex) {
            Logger.getLogger(Record.class.getName()).log(Level.SEVERE, null, ex);
        }
       return record; 
    }
    
    public void copy(T object) {
        this.id = object.id;
    }
    
    void notifyChanged() {
        if (listener != null) {
            listener.onChange(this);
        }
    }
    
    public static interface ChangeListener {
        void onChange(Record record);
    }
    
}
